﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Xml.Linq;
using Microsoft.Phone.Shell;
using Tfs.OnTheRoad;
using Tfs.OnTheRoad.Helpers;
using Tfs.OnTheRoad.Pages;
using Tfs.OnTheRoad.ViewModel;
namespace Tfs_OnTheRoad
{
    /// <summary>
    /// Settings/AccessProfile Page
    /// </summary>
    public partial class SettingsPage : BasePage
    {
        public SettingsPage()
        {
            InitializeComponent();
        }

        SettingsViewModel viewModel = null;

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("Add"))
            {
                viewModel = new SettingsViewModel();
            }
            else
            {
                viewModel = App.SettingsViewModel;
                if (PhoneApplicationService.Current.State.ContainsKey("SettingsSavedToShowHelpOrAbout"))
                {
                    //Restoring the state
                    XElement settings = PhoneApplicationService.Current.State["SettingsSavedToShowHelpOrAbout"] as XElement;
                    if (settings != null)
                        SettingsStorageHelper.ReadSettingViewModel(settings, viewModel);
                    PhoneApplicationService.Current.State.Remove("SettingsSavedToShowHelpOrAbout");
                }
            }
            this.DataContext = viewModel;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            XElement settings = SettingsStorageHelper.SaveSettingViewModel(viewModel);
            PhoneApplicationService.Current.State["SettingsSavedToShowHelpOrAbout"] = settings;
            base.OnNavigatedFrom(e);            
        }

        private void TextChangedUpdateTrigger(object sender, TextChangedEventArgs e)
        {
            TextBox txtbox = sender as TextBox;
            BindingExpression bindingExpression = txtbox.GetBindingExpression(TextBox.TextProperty);
            bindingExpression.UpdateSource();
        }

        private void PasswordChangedUpdateTrigger(object sender, RoutedEventArgs e)
        {
            PasswordBox txtbox = sender as PasswordBox;
            BindingExpression bindingExpression = txtbox.GetBindingExpression(PasswordBox.PasswordProperty);
            bindingExpression.UpdateSource();
        }
    }
}
